package com.cash.app.ui.main.fg.home

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import com.cash.app.R
import com.cash.app.base.BaseActivity
import com.cash.app.constant.AppConstant.AUTH_TYPE_BANK
import com.cash.app.constant.AppConstant.AUTH_TYPE_BASIC
import com.cash.app.constant.AppConstant.AUTH_TYPE_PERSONAL
import com.cash.app.databinding.FgHomeBinding
import com.cash.app.manager.AccountInfoManager
import com.cash.app.manager.GlobalConfigManager
import com.cash.app.manager.GlobalTaskManager
import com.cash.app.manager.LoginManager
import com.cash.app.manager.model.RealProductResponse
import com.cash.app.ui.auth.AuthBankActivity
import com.cash.app.ui.auth.AuthBasicActivity
import com.cash.app.ui.auth.AuthPersonalActivity
import com.cash.app.ui.loan.LoanConfirmActivity
import com.cash.app.ui.loan.LoanConfirmResultActivity
import com.cash.app.ui.main.MainActivity
import com.cash.app.ui.main.fg.home.adapter.GridItem
import com.cash.app.ui.main.fg.home.adapter.HomeGridAdapter
import com.cash.app.ui.main.fg.home.adapter.HomeListAdapter
import com.cash.app.ui.main.fg.home.model.HomeResponse
import com.cash.app.ui.main.fg.home.model.LoanProduct
import com.cash.app.utils.NumberUtils
import com.cash.app.utils.addVerticalSpacing
import com.cash.app.utils.hide
import com.cash.app.utils.visible
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

class HomeFragment : Fragment() {

    private var _binding: FgHomeBinding? = null
    private val binding get() = _binding!!

    private var _homeViewModel: HomeViewModel? = null
    private val homeViewModel get() = _homeViewModel!!

    private val homeAdapter by lazy { HomeListAdapter() }
    private val gridAdapter by lazy { HomeGridAdapter() }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
    ): View {
        _homeViewModel = ViewModelProvider(this)[HomeViewModel::class.java]
        _binding = FgHomeBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        setupRecyclerView()
        setupObservers()
        setupSwipeRefresh()
    }

    override fun onResume() {
        super.onResume()
        fetchHomeData()
    }

    private fun fetchHomeData() {
        homeViewModel.fetchHomeData()
        (requireActivity() as MainActivity).checkAppDialog()
    }

    private fun setupSwipeRefresh() {
        binding.swipeRefreshLayout.setColorSchemeResources(
            R.color.app_theme_color,
        )
        binding.swipeRefreshLayout.setOnRefreshListener {
            binding.swipeRefreshLayout.isRefreshing = true
            fetchHomeData()
        }
    }

    private fun setupRecyclerView() {
        binding.recyclerView.apply {
            layoutManager = LinearLayoutManager(context)
            adapter = homeAdapter
            addVerticalSpacing(resources.getDimensionPixelSize(R.dimen.home_list_item_spacing))
        }
        homeAdapter.onItemApplyClick = { product ->
//            LoanConfirmActivity.start(
//                requireContext(),
//                1,
//                30000,
//                6,
//                "ProductTestName",
//                "http://download.menggaliuang.io/picture/20231201/c123b7e0ba24041d643099dde98073a0.png"
//            )

            startGetCredit(product)
        }
    }

    private var isBasic = false
    private var isPersonal = false
    private var isBank = false

    private fun startGetCredit(product: LoanProduct) {
        val isLoginState = LoginManager.isLogin()
        val activity = requireActivity() as BaseActivity
        activity.startActivityWithLoginCheck({
            GlobalTaskManager.getAccountDetail {
                lifecycleScope.launch(Dispatchers.Main) {
                    isBasic = AccountInfoManager.isAuthCompleted(AUTH_TYPE_BASIC)
                    isPersonal = AccountInfoManager.isAuthCompleted(AUTH_TYPE_PERSONAL)
                    isBank = AccountInfoManager.isAuthCompleted(AUTH_TYPE_BANK)

                    if (!isBasic) {
                        AuthBasicActivity.start(requireContext(), isBasic)
                        return@launch
                    }
                    if (!isPersonal) {
                        AuthPersonalActivity.start(requireContext(), isPersonal)
                        return@launch
                    }
                    if (!isBank) {
                        AuthBankActivity.start(requireContext(), isBank)
                        return@launch
                    }
                    if (isLoginState) { // auth is passed
                        homeViewModel.showRealProduct(product.p_id)
                    }
                }
            }
        })
    }

    private fun setupObservers() {
        homeViewModel.products.observe(viewLifecycleOwner) { rsp ->
            binding.swipeRefreshLayout.isRefreshing = false
            when {
                rsp.products.isEmpty() -> showEmptyState()
                rsp.products.size == 1 -> showSingleProduct(rsp)
                else -> showMultipleProducts(rsp)
            }
        }
        homeViewModel.realProductData.observe(viewLifecycleOwner) { product ->
            jumpToLoanApply(product)
        }
        homeViewModel.fastApplyData.observe(viewLifecycleOwner) { response ->
            LoanConfirmResultActivity.start(requireContext(), response.remark)
        }
    }

    private fun jumpToLoanApply(product: RealProductResponse) {
        if (GlobalConfigManager.isFastApplyEnabled() && product.p_vip != 1) {
            homeViewModel.fastApply(product.p_id)
        } else {
            LoanConfirmActivity.start(
                requireContext(),
                product.p_id,
                product.p_money,
                product.p_peroid,
                product.p_name,
                product.p_icon,
                product.p_vip == 1
            )
        }
    }

    private fun showEmptyState() {
        binding.apply {
            emptyState.visibility = View.VISIBLE
            emptyTip.visibility = View.VISIBLE
            contentArea.visibility = View.GONE
            recyclerView.visibility = View.GONE
        }
    }

    private fun showSingleProduct(rsp: HomeResponse) {
        binding.apply {
            emptyState.visibility = View.GONE
            emptyTip.visibility = View.GONE
            contentArea.visibility = View.VISIBLE
            recyclerView.visibility = View.VISIBLE

            // Show grid content
            gridContent.visibility = View.VISIBLE
            textContent.root.hide()

            // Setup grid
            gridContent.adapter = gridAdapter
            gridAdapter.setData(getGridItems(rsp))

            // Setup list with large item
            homeAdapter.submitList(listOf(rsp.products.first()))
            homeAdapter.setViewType(HomeListAdapter.VIEW_TYPE_LARGE)
            homeAdapter.setCanLoan(rsp.canLoan)
        }
    }

    private fun showMultipleProducts(rsp: HomeResponse) {
        binding.apply {
            emptyState.visibility = View.GONE
            emptyTip.visibility = View.GONE
            contentArea.visibility = View.VISIBLE
            recyclerView.visibility = View.VISIBLE

            // Show text content
            gridContent.visibility = View.GONE
            textContent.root.visible()

            // Setup list with small items
            homeAdapter.submitList(rsp.products)
            homeAdapter.setViewType(HomeListAdapter.VIEW_TYPE_SMALL)
            homeAdapter.setCanLoan(rsp.canLoan)
        }
    }

    private fun getGridItems(rsp: HomeResponse): List<GridItem> {
        val info: LoanProduct = rsp.products.get(0)
        return listOf(
            GridItem(
                iconResId = R.mipmap.post1,
                title = getString(R.string.tip_credit1),
                desc = getString(R.string.tip_credit2, NumberUtils.toRupeeWithComma(info.p_money))
            ), GridItem(
                iconResId = R.mipmap.post2,
                title = getString(R.string.tip_tenure),
                desc = getString(
                    R.string.unit_tenure, info.p_peroid.toString()
                )//getString(R.string.tip_tenure2)
            ), GridItem(
                iconResId = R.mipmap.post3, title = getString(R.string.tip_rate2), desc = getString(
                    R.string.tip_rate3, getString(
                        R.string.unit_percent, info.p_rate
                    )
                )
            ), GridItem(
                iconResId = R.mipmap.post4,
                title = getString(R.string.tip_review),
                desc = getString(R.string.tip_review1)
            )
        )
    }


    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
}